package com.ruoyi.system.utils;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DistanceUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.JiajiaWorker;
import com.ruoyi.system.service.IJiajiaWorkerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class TokenUtil {
    private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    public static  final  String jiajia_reids_token = "jiajia:token:";

    public static  final String jiajia_user_phone_login_code = "jiajia:user:phone_login:code:";

    public static  final String jiajia_worker_phone_login_code = "jiajia:worker:phone_login:code:";

    public static  final String jiajia_worker_phone_register_code = "jiajia:worker:phone_register:code:";

    public static final String gao_de_key = "4d9e007da80609f238ca096e6cce2591";

    public static final String platform_android = "android";
    public static final String platform_ios = "ios";

    public static final String platforms_H5 = "H5";
    public static final String platforms_APP = "app";
    public static final String platforms_MP = "MP";


    private static IJiajiaWorkerService workerService;

    /***
     * 根据客户端传来的token，获取相关用户id
     * @return 用户id
     */
    public static Long getUid(){
        StringRedisTemplate redisTemplate = SpringUtils.getBean(StringRedisTemplate.class);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");

        //根据token,判断是否登陆
        if (!StringUtils.isEmpty(token)){
            String redisToken = redisTemplate.opsForValue().get(jiajia_reids_token+token);
            if (!StringUtils.isEmpty(redisToken)){
                return Long.valueOf(redisToken);
            }
        }
        return 0L;
    }

    /***
     * 获取用户lat
     * @return 用户id
     */
    public static String getLat(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String lat = request.getHeader("lat");
        return lat;
    }

    /***
     * 获取用户lng
     * @return 用户
     */
    public static String getLng(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String lng = request.getHeader("lng");
        return lng;
    }

    /***
     * 获取用户lng
     * @return 用户
     */
    public static String getPlatForm(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String platform = request.getHeader("platform1");
        return platform;
    }


    /***
     * 获取用户登录平台 h5 小程序 App
     * @return 用户
     */
    public static String getPlatForms(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String platform = request.getHeader("platform");
        return platform;
    }

    /**
     * 判断客户端是否登陆
     * @return true or false
     */
    public static boolean isLogin(){
        if (getUid()==0L){
            return false;
        }
        return true;
    }

    //获取距离
    public static String getLuLi(String lat,String lng){

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String latA = request.getHeader("lat");
        String lngA = request.getHeader("lng");

        if (StringUtils.isEmpty(latA) || StringUtils.isEmpty(lngA)){
            String ip = request.getHeader("ip");
            if (StringUtils.isEmpty(ip)){
                return "查询不到定位";
            }
            //根据ip获取经纬度 https://restapi.amap.com/v5/ip?parameters&key=44cc0cba2f6632dbd53a2f9a91445a95&type=4&ip=123.144.28.9
            String rspStr = HttpUtils.sendGet("https://restapi.amap.com/v5/ip", "ip=" + "192.168.10.7" + "&key="+gao_de_key+"&type=4", Constants.UTF8);
            if (StringUtils.isEmpty(rspStr)){
                return "查询定位失败";
            }
            JSONObject obj = JSONObject.parseObject(rspStr);
            String location = obj.getString("location");
            if (StringUtils.isEmpty(location))return "查询定位失败";
            latA = location.split(",")[1];
            lngA = location.split(",")[0];
        }

        return DistanceUtil.getJuLiToKM(lng,lat,lngA, latA);

    }

    //获取距离数字
    public static Float getLuLiNum(String lat,String lng){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //经度纬度接收是反的
        String  lngA= request.getHeader("lng");
        String  latA= request.getHeader("lat");
        if (StringUtils.isEmpty(latA) || StringUtils.isEmpty(lngA)){
            String ip = request.getHeader("ip");
            if (StringUtils.isEmpty(ip)){
                return 999f;
            }
            //根据ip获取经纬度 https://restapi.amap.com/v5/ip?parameters&key=44cc0cba2f6632dbd53a2f9a91445a95&type=4&ip=123.144.28.9
            String rspStr = HttpUtils.sendGet("https://restapi.amap.com/v5/ip", "ip=" + ip + "&key="+gao_de_key+"&type=4", Constants.UTF8);
            if (StringUtils.isEmpty(rspStr)){
                return 999f;
            }
            JSONObject obj = JSONObject.parseObject(rspStr);
            String location = obj.getString("location");
            if (StringUtils.isEmpty(location))return 999f;
            latA = location.split(",")[1];
            lngA = location.split(",")[0];
        }
        int juLi = DistanceUtil.getDistance(lng, lat, lngA, latA);
        return BigDecimal.valueOf(juLi).divide(BigDecimal.valueOf(1000))
                .setScale(2, RoundingMode.HALF_UP).floatValue();
    }

    //逆解析地址
    public static String getAddreseByLocation(){
        String lat= getLat();
        String lng=getLng();
        if (StringUtils.isEmpty(lat)||StringUtils.isEmpty(lng)){
            return "重庆市";
        }
        //根据ip获取经纬度 https://restapi.amap.com/v5/ip?parameters&key=44cc0cba2f6632dbd53a2f9a91445a95&type=4&ip=123.144.28.9
        String rspStr = HttpUtils.sendGet("https://restapi.amap.com/v3/geocode/regeo",  "key="+gao_de_key+"&location="+lng+","+lat, Constants.UTF8);

        JSONObject obj = JSONObject.parseObject(rspStr);
        if (obj.isEmpty()){
            return "重庆市";
        }
        JSONObject a = obj.getJSONObject("regeocode");
        if (a.isEmpty()){
            return "重庆市";
        }
        String address = a.getString("formatted_address");
        if (StringUtils.isEmpty(address)){
            return "重庆市";
        }

        return address;
    }

    //逆解析地址(获取区)
    public static String getQuByLocation(){
        String lat= getLat();
        String lng=getLng();
        if (StringUtils.isEmpty(lat)||StringUtils.isEmpty(lng)){
            return "暂无地址";
        }
        //根据ip获取经纬度 https://restapi.amap.com/v5/ip?parameters&key=44cc0cba2f6632dbd53a2f9a91445a95&type=4&ip=123.144.28.9
        String rspStr = HttpUtils.sendGet("https://restapi.amap.com/v3/geocode/regeo",  "key="+gao_de_key+"&location="+lng+","+lat, Constants.UTF8);

        JSONObject obj = JSONObject.parseObject(rspStr);
        if (obj.isEmpty()){
            return "暂无地址";
        }
        JSONObject a = obj.getJSONObject("regeocode");
        if (a.isEmpty()){
            return "暂无地址";
        }
        JSONObject component = a.getJSONObject("addressComponent");
        if (component.isEmpty()){
            return "暂无地址";
        }

        String city = component.getString("district");
        if (StringUtils.isEmpty(city)){
            return "暂无地址";
        }
        System.out.println("------------------------------"+city+"--------------------------------------------");
        return city;
    }

    public static Float xiaDanJuLi(String lat,String lng,Long workerId){
        //获取技师的经度纬度
        JiajiaWorker jiajiaWorker = workerService.selectJiajiaWorkerById(workerId);
        //经度纬度接收是反的
        String  lngA= jiajiaWorker.getLng();
        String  latA= jiajiaWorker.getLat();
        int juLi = DistanceUtil.getDistance(lng, lat, lngA, latA);
        return BigDecimal.valueOf(juLi).divide(BigDecimal.valueOf(1000))
                .setScale(2, RoundingMode.HALF_UP).floatValue();
    }


    //根据经纬度获取全国行政区域code
    public static String getAdcodeBylatlon(String lat, String lng){
        if (StringUtils.isEmpty(lat)||StringUtils.isEmpty(lng)){
            throw new ServiceException("暂无地址") ;
        }
        String rspStr = HttpUtils.sendGet("https://restapi.amap.com/v3/geocode/regeo",  "key="+gao_de_key+"&location="+lng+","+lat, Constants.UTF8);

        JSONObject obj = JSONObject.parseObject(rspStr);
        if (obj.isEmpty()){
            throw new ServiceException("暂无地址") ;
        }
        JSONObject a = obj.getJSONObject("regeocode");
        if (a.isEmpty()){
            throw new ServiceException("暂无地址") ;
        }
        JSONObject component = a.getJSONObject("addressComponent");
        if (component.isEmpty()){
            throw new ServiceException("暂无地址") ;
        }

        String adcode = component.getString("adcode");
        if (StringUtils.isEmpty(adcode)){
            throw new ServiceException("暂无地址") ;
        }
        //补0 	500101000000
        int length = 12-adcode.length();

         for(int i=0;i<length;i++){
             adcode=adcode+"0";
         }
        return adcode;
    }



}
